package org.smart4j.chapter2.helper;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.chapter2.model.Customer;
import org.smart4j.chapter2.util.CollectionUtil;
import org.smart4j.chapter2.util.PropsUtil;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;


/**
 * 数据库操作助手类
 */
public final class DatabaseHelper {
    private static final ThreadLocal<Connection> CONNECTION_THREAD ;

    private static final QueryRunner QUERY_RUNNER ;

    private static final BasicDataSource DATA_SOURCE;
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(DatabaseHelper.class);



    /**
     * 加载config.properties文件并给常量赋值
     */
    static {
        CONNECTION_THREAD = new ThreadLocal<Connection>();
        QUERY_RUNNER = new QueryRunner();

        Properties conf = PropsUtil.loadProps("config.properties");
        String driver = conf.getProperty("jdbc.driver");
        String url = conf.getProperty("jdbc.url");
        String username = conf.getProperty("jdbc.username");
        String password = conf.getProperty("jdbc.password");

        DATA_SOURCE=new BasicDataSource();
        DATA_SOURCE.setDriverClassName(driver);
        DATA_SOURCE.setUrl(url);
        DATA_SOURCE.setUsername(username);
        DATA_SOURCE.setPassword(password);



    }

    public static void executeSqlFile(String filePath){

        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);//线程加载配置文件
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        try{
            String sql;
            while ((sql=reader.readLine())!=null){
                DatabaseHelper.executeUpdate(sql);
            }
        }catch (Exception e){
            LOGGER.error("execute sql file failure",e);
            throw new RuntimeException(e);
        }
    }



    /**
     * 获取数据库连接
     */
    public static Connection getConnection(){
        Connection  conn= CONNECTION_THREAD.get();//从当前线程里获得连接

        try {
            conn = DATA_SOURCE.getConnection();//创建一个新的连接覆盖掉旧的
        } catch (SQLException e) {
            LOGGER.error("get connection failure",e);//如果出错,抛出无法获取链接
            throw new RuntimeException(e);
        }finally {
            CONNECTION_THREAD.set(conn);//最后将conn存到线程里
        }
        return conn;
    }


    /**
     * 关闭数据库连接
     */
    /*public static void closeConnection(){
        Connection conn = CONNECTION_THREAD.get();//在线程里获取链接conn

        if(conn!=null){//如果不为空进行关闭
            try {
                conn.close();
            } catch (SQLException e) {
                LOGGER.error("close connection failure", e);
                throw new RuntimeException(e);
            }finally {
                CONNECTION_THREAD.remove();//关闭接受从线程里移除
            }
        }
    }
    //使用DBCP,删除finallycloseConnection方法
*/
    /**
     * 查询实体列表(查询多个对象)
     * @param entityClass
     * @param sql
     * @param parmas
     * @param <T>
     * @return
     */
    public static <T> List<T> queryEntityList(Class<T> entityClass,String sql,Object... parmas){
        List<T> entityList;
        try{
            Connection conn = getConnection();//获取连接
            entityList = QUERY_RUNNER.query(conn,sql,new BeanListHandler<T> (entityClass),parmas);//查询数据库
        }catch (SQLException e){
            LOGGER.error("query entity list failure",e);
            throw new RuntimeException(e);
        }
        return entityList;
    }

    /**
     * 查询实体(查询单个实体)
     * @param entityClass
     * @param sql
     * @param params
     * @param <T>
     * @return
     */
    public static <T> T queryEntity(Class<T> entityClass,String sql,Object... params){
        T entity ;
        try{
            Connection conn = getConnection();
            entity = QUERY_RUNNER.query(conn, sql, new BeanHandler<T>(entityClass), params);
        }catch (SQLException e){
            LOGGER.error("query entity failure",e);
            throw new RuntimeException(e);
        }
        return entity;
    }

    /**
     * 执行查询语句(多表查询),没有关闭连接
     * @param sql
     * @param params
     * @return
     */
    public static List<Map<String,Object>> executeQuery(String sql , Object... params){
        List<Map<String,Object>> result;
        try{
            Connection conn = getConnection();
            result = QUERY_RUNNER.query(conn,sql,new MapListHandler(),params);
        }catch (Exception e){
            LOGGER.error("execute  query failure",e);
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 执行更新语句(包括update,insert delete)
     * @param sql
     * @param params
     * @return
     */
    public static int executeUpdate(String sql,Object... params){
        int rows=0;
        try{
            Connection conn = getConnection();
            rows= QUERY_RUNNER.update(conn,sql,params);
        }catch (SQLException e) {
            LOGGER.error("execute Update failure",e);
            throw new RuntimeException(e);
        }
        return rows;
    }




    //得到类的简写名当做表名
    private static String getTableName(Class<?> entityClass){
        return entityClass.getSimpleName();
    }

    /**
     * 插入实体
     * @param entityClass
     * @param fieldMap
     * @param <T>
     * @return
     */
    public static <T> boolean insertEntity(Class<T> entityClass,Map<String,Object> fieldMap){
        if(CollectionUtil.isEmpty(fieldMap)){//判断fieldMap是否为空
            LOGGER.error("can not insert entity:fieldMap is empty");
            return false;
        }
        String sql ="INSERT INTO "+getTableName(entityClass);//inser to

        StringBuilder colums = new StringBuilder("(");//
        StringBuilder values = new StringBuilder("(");
        for (String fieldName:fieldMap.keySet() ) {
           colums.append(fieldName).append(", ");
           values.append("?, ");
        }
        colums.replace(colums.lastIndexOf(", "),colums.length(),")");
        values.replace(values.lastIndexOf(", "),values.length(),")");
        sql+= colums+" VALUES "+values;
        Object[] params = fieldMap.values().toArray();
        return executeUpdate(sql,params) == 1;
    }

    /**
     * 更新实体
     * @param entityClass
     * @param id
     * @param fieldMap
     * @param <T>
     * @return
     */
    public static <T> boolean updateEntity(Class<T> entityClass,long id,Map<String,Object> fieldMap){
        if(CollectionUtil.isEmpty(fieldMap)){
            LOGGER.error("can not update entity: fileldMap is empty");
            return false;
        }
        String sql = "UPDATE "+getTableName(entityClass) + " SET ";
        StringBuilder columns = new StringBuilder();
        for (String fieldName: fieldMap.keySet()) {
            columns.append(fieldName).append("=?, ");
        }
        sql+=columns.substring(0,columns.lastIndexOf(", ")) + " WHERE id =? ";

        List<Object> paramList = new ArrayList<Object>();
        paramList.addAll(fieldMap.values());
        paramList.add(id);
        Object[] params = paramList.toArray();
        return executeUpdate(sql,params)==1;
    }

    /**
     * 删除实体
     * @param entityClass
     * @param id
     * @param <T>
     * @return
     */
    public static <T> boolean deleteEntity(Class<T> entityClass ,long id){
       String sql ="DELETE FROM "+getTableName(entityClass) + " WHERE id = ?";
       return executeUpdate(sql,id)==1;
    }

}
